package com.epfresh.supplier.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.epfresh.api.entity.RequestEntityMapSupply;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.MsgView;
import com.epfresh.api.widget.tablayout.utils.UnreadMsgUtils;
import com.epfresh.supplier.R;
import com.epfresh.supplier.entity.StoreCategory;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ProductAddStoreCategoryActivity extends BaseActivity {


    private EditText ed;
    private TextView tvAdd;
    private ListView lv;
    private StoreCategoryAdapter adapter;

    private List<StoreCategory> list = new ArrayList<>();

    private String storeCategoryId;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_add_store_category);
        if (savedInstanceState != null) {
            getIntent().putExtra("productId", savedInstanceState.getString("productId"));
            getIntent().putExtra("storeCategoryId", savedInstanceState.getString("storeCategoryId"));

        }

        storeCategoryId = getIntent().getStringExtra("storeCategoryId");
        initView();
    }

    @Override
    protected View getToolBar() {
        View actionbar = this.inflaterView(R.layout.toolbar_product_add, null);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(-1, this.getResources().getDimensionPixelSize(com.epfresh.api.R.dimen.action_bar_height));
        actionbar.setLayoutParams(lp);

        ed = (EditText) actionbar.findViewById(R.id.et_content);
        tvAdd = (TextView) actionbar.findViewById(R.id.tv_search);
        ivBack = (ImageView) actionbar.findViewById(R.id.iv_back);
        tvBack.setVisibility(View.VISIBLE);

        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        ed.setHint("请添加新店铺分类");
        ed.setFilters(new InputFilter[]{new InputFilter.LengthFilter(8)});
        tvAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                add();
            }
        });

        return actionbar;
    }

    private void add() {

        if (ed.getText().toString().length() > 0) {
            requestAdd(ed.getText().toString());
        } else {
            toast("请添加新店铺分类");
        }
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {

        outState.putString("productId", getIntent().getStringExtra("productId"));
        outState.putString("storeCategoryId", getIntent().getStringExtra("storeCategoryId"));
        super.onSaveInstanceState(outState);
    }


    private void initView() {

        lv = (ListView) findViewById(R.id.lv);

        adapter = new StoreCategoryAdapter(this);


        lv.setAdapter(adapter);

        request();
    }

    public void updateStatus() {
        if (storeCategoryId != null && !"".equals(storeCategoryId)) {
            for (int i = 0; i < list.size(); i++) {
                StoreCategory storeCategory = list.get(i);
                if (storeCategoryId.equals(storeCategory.getId())) {
                    storeCategory.setSelect(true);
                } else {
                    storeCategory.setSelect(false);
                }
            }
        }
    }


    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.tv_btn:

                break;
        }
    }

    public void selectStore(StoreCategory storeCategory) {

        if (storeCategory != null && storeCategory.isSelect()) {
            Intent intent = new Intent();
            intent.putExtra("storeCategoryId", storeCategory.getId());
            intent.putExtra("storeCategoryName", storeCategory.getName());
            setResult(RESULT_OK, intent);
            finish();
        }
    }

    public void requestAdd(String name) {

        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_store_category_add);

        RequestEntityMapSupply.putParameter("name", name);
        request(RequestEntityMapSupply, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_store_category_add, onCategoryAddRequestListener);

    }


    private OnRequestListener<Map<String, Boolean>> onCategoryAddRequestListener = new OnRequestListener<Map<String, Boolean>>() {
        @Override
        public Map<String, Boolean> jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, new TypeToken<Map<String, Boolean>>() {
            }.getType());
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            toast("添加失败");
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            toast("添加失败");
        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<Map<String, Boolean>> response, Object tag) {


            Map<String, Boolean> responseElement = response.getResponseElement();

            if (responseElement != null && responseElement.size() > 0) {

                ed.setText("");
                request();
            }
        }
    };

    public void requestModify(String name, String id) {

        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_store_category_modify);

        RequestEntityMapSupply.putParameter("name", name);
        RequestEntityMapSupply.putParameter("id", id);
        request(RequestEntityMapSupply, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_store_category_modify, onCategoryModifyRequestListener);

    }


    private OnRequestListener<Map<String, Boolean>> onCategoryModifyRequestListener = new OnRequestListener<Map<String, Boolean>>() {
        @Override
        public Map<String, Boolean> jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, new TypeToken<Map<String, Boolean>>() {
            }.getType());
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            toast("修改失败");
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {

            toast("修改失败");
        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<Map<String, Boolean>> response, Object tag) {


            Map<String, Boolean> responseElement = response.getResponseElement();

            if (responseElement != null && responseElement.size() > 0) {

                request();
            }
        }
    };

    public void request() {

        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_store_category_list);

        request(RequestEntityMapSupply, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_store_category_list, onCategoryTreeRequestListener);

    }


    private OnRequestListener<List<StoreCategory>> onCategoryTreeRequestListener = new OnRequestListener<List<StoreCategory>>() {
        @Override
        public List<StoreCategory> jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, new TypeToken<List<StoreCategory>>() {
            }.getType());
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<List<StoreCategory>> response, Object tag) {


            List<StoreCategory> responseElement = response.getResponseElement();

            if (responseElement != null && responseElement.size() > 0) {


                list.clear();
                list.addAll(responseElement);
                updateStatus();
                adapter.notifyDataSetChanged();


            }
        }
    };


    public class StoreCategoryAdapter extends BaseAdapter implements View.OnClickListener {

        Context context;

        public StoreCategoryAdapter(Context context) {
            this.context = context;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int i) {
            return i;
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            ViewHolder vh = null;
            if (view == null) {
                vh = new ViewHolder();
                view = LayoutInflater.from(context).inflate(R.layout.item_list_store_category, null, false);

                vh.tvContent = (TextView) view.findViewById(R.id.tv_content);
                vh.tvFinish = (TextView) view.findViewById(R.id.tv_finish);
                vh.ed = (EditText) view.findViewById(R.id.ed);
                vh.ivSelect = (ImageView) view.findViewById(R.id.iv_flag);
                vh.ivEdit = (ImageView) view.findViewById(R.id.iv_edit);

                vh.msgView = (MsgView) view.findViewById(R.id.msg);
                vh.vContent = view.findViewById(R.id.rl_content);
                vh.vEdit = view.findViewById(R.id.rl_edit);
                view.setTag(vh);
            } else {
                vh = (ViewHolder) view.getTag();
            }

            StoreCategory storeCategory = list.get(i);

            vh.tvContent.setText(storeCategory.getName());
            if (storeCategory.isSelect()) {
                vh.ivSelect.setImageResource(R.mipmap.register_read);
            } else {
                vh.ivSelect.setImageResource(R.mipmap.register_unread);
            }

            if (storeCategory.isEdit()) {
                vh.vEdit.setVisibility(View.VISIBLE);
                vh.vContent.setVisibility(View.GONE);
            } else {
                vh.vEdit.setVisibility(View.GONE);
                vh.vContent.setVisibility(View.VISIBLE);
            }

            vh.ed.setText(storeCategory.getName());
            vh.ed.setSelection(vh.ed.length());


            UnreadMsgUtils.show(vh.msgView, storeCategory.getQuantity());
            vh.ivEdit.setTag(R.id.item_key_position, i);
            vh.ivEdit.setOnClickListener(this);
            vh.ivSelect.setTag(R.id.item_key_position, i);
            vh.ivSelect.setOnClickListener(this);
            vh.tvFinish.setTag(R.id.item_key_position, i);
            vh.tvFinish.setTag(R.id.item_key_view, vh.ed);
            vh.tvFinish.setOnClickListener(this);

            return view;
        }


        @Override
        public void onClick(View view) {

            Object tag = view.getTag(R.id.item_key_position);
            if (tag != null && tag instanceof Integer) {
                int position = (int) tag;

                StoreCategory storeCategory = list.get(position);
                if (view.getId() == R.id.tv_finish) {
                    storeCategory.setEdit(false);
                    String s = ((EditText) (view.getTag(R.id.item_key_view))).getText().toString();
                    if (s != null && !"".equals(s)) {
//                        storeCategory.setName(s);

//                        toast("" + s);
                        requestModify(s, storeCategory.getId());
                    } else {
                        T.toast("名称不能为空");
                    }

                } else if (view.getId() == R.id.iv_flag) {
                    boolean select = !storeCategory.isSelect();
                    clearAllSelect();
                    storeCategory.setSelect(select);

                    selectStore(storeCategory);

                } else if (view.getId() == R.id.iv_edit) {
                    boolean edit = storeCategory.isEdit();

                    storeCategory.setEdit(!edit);
                }
                notifyDataSetChanged();
            }

        }

        public void clearAllSelect() {
            for (StoreCategory s : list) {
                s.setSelect(false);
            }
        }
    }


    public class ViewHolder {

        TextView tvContent;
        TextView tvFinish;
        EditText ed;
        ImageView ivSelect;
        ImageView ivEdit;
        MsgView msgView;
        View vContent;
        View vEdit;

    }
}
